//
//  RichTextNode.swift
//  xzclient
//
//  Created by zhuxietong on 2021/5/14.
//

import Foundation
import Eelay
import RxSwift
import Atributika
//import AttributedString

open class RichSet{
    
    public var linkCss:[UICss] = [.font(.systemFont(ofSize: 13)),.color(.systemBlue)]
    public var contentCss:[UICss] = [.font(.systemFont(ofSize: 13)),.color(._foreground)]
    public var markTags = [
        "a","zxuser"
    ]
    
    public var text = ""
    open var components:[String]{
        let raw = "<%cap%>" + self.text
        let reg =  Regex("(\\(%xz(.*?(\"name\").*?(\"uid\").*?)%xz\\)?)")
        let users = reg.allMatches(in: raw).map({ (r) -> String in
            return r.matchedString
        })
        
        let full = "\(raw)".replacingAll(matching: reg, with: "<%user%>")
        let components = full.components(separatedBy: "<%user%>").filter({$0.count > 0})
        var list = [String]()
        for i in 0..<components.count {
            if i == 0{
                let first = components[0].replacingOccurrences(of: "<%cap%>", with: "")
                if first.count > 0{
                    list.append(first)
                }
            }else{
                list.append(components[i])
            }
            if i < users.count{
                list.append(users[i])
            }
        }
//        items.removeFirst()
        return list
    }
    public init(text:String) {
        self.text = text
    }
    
    public weak var atController:UIViewController? = nil
    
    public var font:UIFont{
        return contentCss.font
    }
//    var attributedString:AttributedString{
//        var vs:AttributedString = .init("".ui.astring)
//        let comps = components
//        for str in comps {
//            if str.hasPrefix("(%xz"){
//                let jsonStr = str.replacingOccurrences(of: "(%xz", with: "").replacingOccurrences(of: "%xz)", with: "")
//                let json = jsonStr.JsonDictionary ?? NSMutableDictionary()
//                let id = json["uid",""]
//                let attr:AttributedString = .init(string:  "@" + json["name",""], .foreground(.systemBlue),.font(font),.action {[weak self] in
////                    print("atController___KKK)|",self?.atController)
//                    AppLink.open("user/home?id=\(id)",at: self?.atController)
//
//
//                })
//                vs = vs + attr
//            }else{
//                let attr:AttributedString = .init(string: str,.foreground(._foreground),.font(font))
//                vs = vs + attr
//            }
//        }
//        return vs
//    }
    
    open var attributedText:AttributedText{
//        let comps = components.map { (str) -> String in
//            if str.hasPrefix("(%xz"){
//                let jsonStr = str.replacingOccurrences(of: "(%xz", with: "").replacingOccurrences(of: "%xz)", with: "")
//                let json = jsonStr.JsonDictionary ?? NSMutableDictionary()
//                let id = json["uid",""]
//                return "<xzuser href=\"user/home?id=\(id)\">@\(json["name",""])</xzuser>"
//            }
//            return str
//        }
    
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpace

        let all = Style.font(font).foregroundColor(contentCss.color, .normal).paragraphStyle(paragraphStyle)
        
//        let tags = markTags.map { tag in
//            return Style(tag)
//                .foregroundColor(linkCss.color, .normal)
//                .foregroundColor(.init(shex: "#888"), .highlighted)
//        }
        let link = Style("xzuser")
            .foregroundColor(linkCss.color, .normal)
            .foregroundColor(.init(shex: "#888"), .highlighted)
        let a = Style("a")
            .foregroundColor(linkCss.color, .normal)
            .foregroundColor(.init(shex: "#888"), .highlighted)



//        let str = text.replacingAll(matching: "(\\(%xz(.*?(\"name\").*?\"(.*?)\".*?(\"uid\").*?(\\d+).*?)%xz\\)?)", with: "<a href=\"$6\">@$4</a>")
        let attr = text
            .style(tags: link,a)
            .styleAll(all)
        return attr
    }
    
    public var lineSpace:CGFloat = 4
    open var nsAttributedString:NSAttributedString{
        var str = text.replacingAll(matching: "(<\\w+\\s+?.+?>)(.*?)(</\\w+>)", with: "$2")
        str = str.replacingAll(matching: "(\\(%xz(.*?(\"name\").*?\"(.*?)\".*?(\"uid\").*?(\\d+).*?)%xz\\)?)", with: "@$4")
        

        let vs:NSMutableAttributedString = str.ui.font(font: font).lineSpace(lineSpace).color(color: .clear).astring
        
//        let comps = components
//        for str in comps {
//            if str.hasPrefix("(%xz") && str.hasSuffix("%xz)"){
//                let jsonStr = str.replacingOccurrences(of: "(%xz", with: "").replacingOccurrences(of: "%xz)", with: "")
//                let json = jsonStr.JsonDictionary ?? NSMutableDictionary()
//                let attr:NSMutableAttributedString =  ("@" + json["name",""]).ui.lineSpace(lineSpace).font(font: font).color(color: .clear).astring
//                vs = vs + attr
//            }else if str.mach("(<\\w+\\s+?.+?>)(.*?)(</\\w+>)"){
////                (<\\w+\\s+?.+?>)(.*?)(</\\w+>)
//                let astr = str.replacingAll(matching: "(<\\w+\\s+?.+?>)(.*?)(</\\w+>)", with: "$2")
//                vs = vs + astr.ui.font(font: font).lineSpace(lineSpace).color(color: .red).astring
//
//            }
//            else{
//                let astr = str.replacingAll(matching: "(<\\w+\\s+?.+?>)(.*?)(</\\w+>)", with: "$2")
//                vs = vs + astr.ui.font(font: font).lineSpace(lineSpace).color(color: .red).astring
//
////                vs = vs + str.ui.font(font: font).lineSpace(lineSpace).color(color: .red).astring
//            }
//        }
        return vs
    }
    
}


open class RichTextNode:MoDisplayNode{
    
    public var linkCss:[UICss] = [.font(.systemFont(ofSize: 13)),.color(.systemBlue)]{
        didSet{
            richSet.linkCss = linkCss
        }
    }
    public var contentCss:[UICss] = [.font(.systemFont(ofSize: 13)),.color(._foreground)]{
        didSet{
            richSet.contentCss = contentCss
        }
    }

    public var text:String = ""{
        didSet{
            richSet.linkCss = linkCss
            richSet.contentCss = contentCss
            richSet.text = text
            label.attributedText = richSet.attributedText
            sizeNode.attributedText = richSet.nsAttributedString
        }
    }
    public var clickTag:(_:NSMutableDictionary)->Void = {_ in}
    
    open override func addLayoutRules() {
        sizeNode.maximumNumberOfLines = 0
        sizeNode.truncationMode = .byTruncatingTail
        label.numberOfLines = 0
        clickTag = {
            [weak self]tag in
            AppLink.open(tag["href",""],at: self?.mo.controller)
        }
        label.onClick = {[weak self] label, detection in
            switch detection.type {
            case .tag(let tag):
                let atr = tag.attributes.mutable_dictionary
                self?.clickTag(atr)
//                AppLink.open(atr["href",""],at: self?.richSet.atController)
                break
            default:
                break
            }
        }
//        backgroundColor = ._1blue
//        label.lineBreakMode = .byTruncatingTail
//        label.lineBreakMode = .byWordWrapping
    }
    
    public var richSet = RichSet(text: "")
    
    public let sizeNode = ASTextNode2()
    public let displayNode = ASDisplayNode { () -> UIView in
        return AttributedLabel()
    }
    public var label:AttributedLabel{
        return displayNode.view as! AttributedLabel
    }
    
    open override func specGetter() -> _Spec {
        return _Spec.inset([], [2,0,2,0], child: sizeNode.Spec).addOver(displayNode.Spec)
    }
    
}
